package com.ypz.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ypz.reggie.common.R;
import com.ypz.reggie.entity.User;
import com.ypz.reggie.service.UserService;
import com.ypz.reggie.utils.SMSUtils;
import com.ypz.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 移动端用户请求验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();

        //小特色功能，每个电话号码只能发一次短信
//        if (phone != null){
//            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
//            lqw.eq(phone!=null,User::getPhone,phone);
//            User one = userService.getOne(lqw);
//
//            if (one != null){
//                System.out.println("每个电话号码只能接受一次短信");
//                return R.error("每个电话号码只能接受一次短信");
//            }
//
//        }

        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info(code);
           // SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",phone,code);

//            session.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone,code,5l, TimeUnit.MINUTES);

            return R.success("手机短信发送成功");
        }

        return R.error("手机短信发送失败");

    }

    /**
     * 移动端用户登录
     *
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {

        //获取请求手机号
        String phone = map.get("phone").toString();

        //获取请求验证码
        String code = map.get("code").toString();

        //获取session中的验证码
//        String sessionCode = session.getAttribute(phone).toString();
        String sessionCode = redisTemplate.opsForValue().get(phone).toString();

        if (phone != null && code != null && sessionCode != null && code.equals(sessionCode)) {
            //如果对比成功则登录成功

            //查找数据库，是否有该用户
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone, phone);
            User user = userService.getOne(lqw);

            //如果是新用户自动注册，存入数据库
            if (user == null) {
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }

            //因为过滤器，所以加这句
            session.setAttribute("user",user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }

        return R.error("登录失败");

    }

    /**
     * 退出登录
     * @return
     */
    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){

        session.removeAttribute("user");

        return R.success("已退出");
    }
}
